import React, { useState, useEffect } from 'react';
import './AISettings.css';
import aiService from '../utils/aiService';

const AISettings = ({ onSettingsChange, isVisible, onClose }) => {
  const [config, setConfig] = useState({
    apiUrl: '',
    apiKey: '',
    model: 'gpt-3.5-turbo',
    enabled: false
  });
  
  const [isExpanded, setIsExpanded] = useState(false);
  const [testStatus, setTestStatus] = useState('');
  const [isTesting, setIsTesting] = useState(false);

  // 预设的AI服务配置
  const presets = {
    openai: {
      name: 'OpenAI',
      apiUrl: 'https://api.openai.com/v1/chat/completions',
      model: 'gpt-3.5-turbo',
      description: '官方OpenAI服务'
    },
    deepseek: {
      name: 'DeepSeek',
      apiUrl: 'https://api.deepseek.com/v1/chat/completions',
      model: 'deepseek-chat',
      description: '高性价比的国产AI模型'
    },
    claude: {
      name: 'Claude (via OpenRouter)',
      apiUrl: 'https://openrouter.ai/api/v1/chat/completions',
      model: 'anthropic/claude-3-haiku',
      description: '通过OpenRouter使用Claude'
    },
    custom: {
      name: '自定义',
      apiUrl: '',
      model: '',
      description: '自定义API配置'
    }
  };

  // 从本地存储加载配置
  useEffect(() => {
    const savedConfig = localStorage.getItem('ai-settings');
    if (savedConfig) {
      try {
        const parsed = JSON.parse(savedConfig);
        setConfig(parsed);
      } catch (error) {
        console.error('Failed to parse AI settings:', error);
      }
    }
  }, []);

  // 保存配置到本地存储
  const saveConfig = (newConfig) => {
    localStorage.setItem('ai-settings', JSON.stringify(newConfig));
    setConfig(newConfig);
    if (onSettingsChange) {
      onSettingsChange(newConfig);
    }
  };

  const handlePresetSelect = (presetKey) => {
    const preset = presets[presetKey];
    const newConfig = {
      ...config,
      apiUrl: preset.apiUrl,
      model: preset.model
    };
    setConfig(newConfig);
  };

  const handleInputChange = (field, value) => {
    const newConfig = { ...config, [field]: value };
    setConfig(newConfig);
  };

  const handleSave = () => {
    saveConfig(config);
    setTestStatus('配置已保存');
    setTimeout(() => setTestStatus(''), 2000);
  };

  const testConnection = async () => {
    if (!config.apiUrl || !config.apiKey) {
      setTestStatus('请填写API地址和密钥');
      return;
    }

    setIsTesting(true);
    setTestStatus('测试连接中...');

    try {
      const response = await fetch(config.apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${config.apiKey}`
        },
        body: JSON.stringify({
          model: config.model,
          messages: [
            { role: 'user', content: 'Test connection' }
          ],
          max_tokens: 10
        })
      });

      if (response.ok) {
        setTestStatus('✅ 连接成功！');
        const newConfig = { ...config, enabled: true };
        saveConfig(newConfig);
      } else {
        const errorData = await response.json().catch(() => ({}));
        setTestStatus(`❌ 连接失败: ${response.status} ${errorData.error?.message || response.statusText}`);
      }
    } catch (error) {
      setTestStatus(`❌ 连接错误: ${error.message}`);
    } finally {
      setIsTesting(false);
      setTimeout(() => setTestStatus(''), 5000);
    }
  };

  const handleToggleEnabled = () => {
    const newConfig = { ...config, enabled: !config.enabled };
    saveConfig(newConfig);
  };

  const handleClearCache = () => {
    const clearedCount = aiService.clearAllTranslationCache();
    setTestStatus(`🗑️ 已清除 ${clearedCount} 条翻译缓存`);
    setTimeout(() => setTestStatus(''), 3000);
  };

  if (!isVisible) return null;

  return (
    <div className="ai-settings-overlay" onClick={onClose}>
      <div className="ai-settings-modal" onClick={e => e.stopPropagation()}>
        <div className="ai-settings-header">
          <h3>🤖 AI翻译设置</h3>
          <button className="close-btn" onClick={onClose}>×</button>
        </div>

        <div className="ai-settings-content">
          <div className="setting-group">
            <label>
              <input
                type="checkbox"
                checked={config.enabled}
                onChange={handleToggleEnabled}
              />
              启用AI翻译功能
            </label>
          </div>

          <div className="setting-group">
            <label>预设配置：</label>
            <div className="preset-buttons">
              {Object.entries(presets).map(([key, preset]) => (
                <button
                  key={key}
                  className="preset-btn"
                  onClick={() => handlePresetSelect(key)}
                  title={preset.description}
                >
                  {preset.name}
                </button>
              ))}
            </div>
          </div>

          <div className="setting-group">
            <label>API地址：</label>
            <input
              type="text"
              placeholder="https://api.openai.com/v1/chat/completions"
              value={config.apiUrl}
              onChange={(e) => handleInputChange('apiUrl', e.target.value)}
              className="setting-input"
            />
          </div>

          <div className="setting-group">
            <label>API密钥：</label>
            <input
              type="password"
              placeholder="sk-..."
              value={config.apiKey}
              onChange={(e) => handleInputChange('apiKey', e.target.value)}
              className="setting-input"
            />
          </div>

          <div className="setting-group">
            <label>模型名称：</label>
            <input
              type="text"
              placeholder="gpt-3.5-turbo"
              value={config.model}
              onChange={(e) => handleInputChange('model', e.target.value)}
              className="setting-input"
            />
          </div>

          <div className="setting-actions">
            <button
              className="test-btn"
              onClick={testConnection}
              disabled={isTesting || !config.apiUrl || !config.apiKey}
            >
              {isTesting ? '测试中...' : '测试连接'}
            </button>
            <button className="save-btn" onClick={handleSave}>
              保存配置
            </button>
            <button className="clear-cache-btn" onClick={handleClearCache}>
              清除翻译缓存
            </button>
          </div>

          {testStatus && (
            <div className={`test-status ${testStatus.includes('✅') ? 'success' : testStatus.includes('❌') ? 'error' : 'info'}`}>
              {testStatus}
            </div>
          )}

          <div className="ai-settings-help">
            <details>
              <summary>💡 配置说明</summary>
              <div className="help-content">
                <h4>支持的AI服务：</h4>
                <ul>
                  <li><strong>OpenAI</strong>: 需要OpenAI API密钥</li>
                  <li><strong>DeepSeek</strong>: 国产模型，性价比高</li>
                  <li><strong>Claude</strong>: 通过OpenRouter等代理使用</li>
                  <li><strong>其他</strong>: 任何兼容OpenAI格式的API</li>
                </ul>
                <h4>功能说明：</h4>
                <ul>
                  <li>🌐 一键翻译整个字幕文件</li>
                  <li>📚 单句翻译和语法解析</li>
                  <li>📖 词汇解释和例句教学</li>
                  <li>💾 翻译结果本地缓存</li>
                </ul>
              </div>
            </details>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AISettings;